<!DOCTYPE html>
<html lang="en" class="h-full" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paperless-AI Dashboard</title>
    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.0/css/all.min.css">
    <link rel="stylesheet" href="css/dashboard.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
</head>
<body class="h-full">
    <button id="themeToggle" class="theme-toggle">
        <i class="fas fa-moon dark:fas fa-sun"></i>
    </button>

    <div class="layout-container">
        <button id="mobileMenuButton" class="mobile-menu-button">
            <i class="fas fa-bars"></i>
        </button>
        <!-- Sidebar -->
        <div id="sidebarOverlay" class="sidebar-overlay"></div>
        <aside class="sidebar">
            <div class="sidebar-header">
                    <img src="/favicon.ico" class="no-invert" alt="Paperless AI Logo" style="height: 60px;">
                <h1 class="brand-title">Paperless-AI<small style="display: block;"><%= version %></small></h1>
            </div>

            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="/dashboard" class="sidebar-link active">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="/manual" class="sidebar-link">
                            <i class="fas fa-file-alt"></i>
                            <span>Manual</span>
                        </a>
                    </li>
                    <li>
                        <a href="/chat" class="sidebar-link">
                            <i class="fa-solid fa-comment"></i>
                            <span>Chat</span>
                        </a>
                    </li>
                    <li>
                        <a href="/rag" class="sidebar-link">
                            <i class="fa-solid fa-comment"></i>
                            <span>RAG Chat</span>
                        </a>
                    </li>
                    <li>
                        <a href="/playground" class="sidebar-link">
                            <i class="fa-solid fa-flask-vial"></i>
                            <span>Playground</span>
                        </a>
                    </li>
                    <li>
                        <a href="/history" class="sidebar-link">
                            <i class="fa-solid fa-clock-rotate-left"></i>
                            <span>History</span>
                        </a>
                    </li>
                    <li>
                        <a href="/settings" class="sidebar-link">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                        </a>
                    </li>
                    <li>
                        <a href="/logout" class="sidebar-link">
                            <i class="fa-solid fa-right-from-bracket"></i>
                            <span>Logout</span>
                        </a>
                    </li>
                </ul>
                <a href="https://github.com/clusterzx/paperless-ai" 
                    class="github-button" 
                    style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);">
                    <span class="star-button">
                        <svg class="star-icon" height="16" width="16" viewBox="0 0 16 16">
                            <path d="M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.75.75 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25z"></path>
                        </svg>
                        Star
                    </span>
                    <span id="starCount" class="star-count">1.2k</span>
                </a>
                <p style="position: absolute; bottom: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: #555; text-align: center;">
                    Please support us on GitHub
                </p>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <div class="content-wrapper">
                <div class="content-header flex items-center justify-between">
                    <h2 class="content-title">Dashboard Overview</h2>
                    <div class="flex items-center gap-4">
                        <div id="updateNotification" class="hidden fixed bottom-4 right-4 z-50">
                            <a href="https://github.com/clusterzx/paperless-ai/releases/" target="_blank" 
                               class="group flex items-center gap-3 bg-white px-4 py-3 rounded-xl shadow-lg border border-gray-100 hover:shadow-xl transition-all duration-300">
                                <div class="flex items-center justify-center w-8 h-8 bg-blue-100 rounded-lg">
                                    <i class="fas fa-arrow-up text-blue-500"></i>
                                </div>
                                <div class="flex flex-col">
                                    <span class="text-sm font-medium text-gray-900">Update Available</span>
                                    <span class="text-xs text-gray-500">Click to download version <span id="latestVersion"></span></span>
                                </div>
                                <i class="fas fa-chevron-right text-gray-400 group-hover:text-gray-600 group-hover:transform group-hover:translate-x-1 transition-all duration-300"></i>
                            </a>
                        </div>
                        <button 
                            id="scanButton" 
                            class="flex items-center gap-2 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors"
                            onclick="triggerScan()"
                        >
                            <i class="fas fa-sync-alt"></i>
                            <span>Scan Now</span>
                        </button>
                        <!-- Success message toast -->
                        <div id="successToast" class="hidden fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg transition-opacity">
                            <div class="flex items-center gap-2">
                                <i class="fas fa-check"></i>
                                <span>Scan completed successfully!</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Top Cards -->
                <div class="card-grid">
                    <!-- Document Chart -->
                    <div class="material-card col-span-2">
                        <h3 class="card-title">Document Processing Status</h3>
                        <div class="flex items-center">
                            <div class="w-1/2">
                                <canvas id="documentChart" height="200"></canvas>
                            </div>
                            <div class="w-1/2 pl-6">
                                <div class="stats-legend">
                                    <div class="stat-item">
                                        <div class="flex items-center justify-between">
                                            <div class="flex items-center">
                                                <div class="w-3 h-3 rounded-full bg-blue-500 mr-2"></div>
                                                <span>AI Processed</span>
                                            </div>
                                            <span class="font-semibold"><%= paperless_data.processedDocumentCount %></span>
                                        </div>
                                    </div>
                                    <div class="stat-item mt-4">
                                        <div class="flex items-center justify-between">
                                            <div class="flex items-center">
                                                <div class="w-3 h-3 rounded-full bg-gray-200 mr-2"></div>
                                                <span>Unprocessed</span>
                                            </div>
                                            <span class="font-semibold"><%= paperless_data.documentCount - paperless_data.processedDocumentCount %></span>
                                        </div>
                                    </div>
                                    <div class="total-stats mt-6 pt-4 border-t">
                                        <div class="text-sm text-gray-600">Total Documents</div>
                                        <div class="text-2xl font-bold"><%= paperless_data.documentCount %></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics Card -->
                    <div class="material-card">
                        <h3 class="card-title">System Statistics</h3>
                        <div class="space-y-6">
                            <div class="stat-box cursor-pointer hover:shadow-lg transition-all" onclick="showTagDetails()">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center">
                                        <div class="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center mr-3">
                                            <i class="fas fa-tags text-blue-500"></i>
                                        </div>
                                        <div>
                                            <div class="text-sm text-gray-600">Total Tags</div>
                                            <div class="text-xl font-bold"><%= paperless_data.tagCount %></div>
                                        </div>
                                    </div>
                                    <i class="fas fa-chevron-right text-gray-400"></i>
                                </div>
                            </div>
                            <div class="stat-box cursor-pointer hover:shadow-lg transition-all" onclick="showCorrespondentDetails()">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center">
                                        <div class="w-10 h-10 rounded-lg bg-purple-100 flex items-center justify-center mr-3">
                                            <i class="fas fa-building text-purple-500"></i>
                                        </div>
                                        <div>
                                            <div class="text-sm text-gray-600">Correspondents</div>
                                            <div class="text-xl font-bold"><%= paperless_data.correspondentCount %></div>
                                        </div>
                                    </div>
                                    <i class="fas fa-chevron-right text-gray-400"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Modal Template -->
                    <div id="detailsModal" class="modal hidden">
                        <div class="modal-overlay"></div>
                        <div class="modal-container">
                            <div class="modal-header">
                                <h3 class="modal-title"></h3>
                                <button class="modal-close">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <div class="modal-content">
                                <div class="modal-loader hidden">
                                    <div class="loader"></div>
                                </div>
                                <div class="modal-data"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Token Usage Card -->
                    <div class="material-card">
                        <h3 class="card-title">AI Token Usage</h3>
                        <div class="space-y-4">
                            <div class="p-4 bg-blue-50 rounded-lg">
                                <div class="flex items-center justify-between mb-2">
                                    <span class="text-sm text-gray-600">Average Token Usage per Document</span>
                                </div>
                                <div class="mt-2 text-sm">
                                    <div class="flex items-center justify-between mb-2">
                                        <span>Prompt Tokens:</span>
                                        <span class="font-semibold"><%= Math.round(openai_data.averagePromptTokens) %></span>
                                    </div>
                                    <div class="flex items-center justify-between mb-2">
                                        <span>Completion Tokens:</span>
                                        <span class="font-semibold"><%= Math.round(openai_data.averageCompletionTokens) %></span>
                                    </div>
                                    <div class="flex items-center justify-between pt-2 border-t">
                                        <span class="font-medium">Average Total:</span>
                                        <span class="font-semibold"><%= Math.round(openai_data.averageTotalTokens) %></span>
                                    </div>
                                </div>
                            </div>
                            <div class="grid grid-cols-1 gap-4">
                                <div class="p-4 bg-gray-50 rounded-lg">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <div class="text-sm text-gray-600">Total Tokens Used</div>
                                            <div class="text-xl font-bold"><%= openai_data.tokensOverall.toLocaleString() %></div>
                                        </div>
                                        <div class="text-right">
                                            <div class="text-sm text-gray-600">Documents Processed</div>
                                            <div class="text-xl font-bold"><%= paperless_data.processedDocumentCount.toLocaleString() %></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-grid mt-6">
                    <!-- Task Runner Status -->
                    <div class="material-card col-span-2">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="card-title mb-0">Task Runner Status</h3>
                            <span id="statusLastUpdated" class="text-sm text-gray-500"></span>
                        </div>

                        <!-- Active Processing Card -->
                        <div class="bg-white rounded-xl border border-gray-100 p-6 mb-4">
                            <div id="processingContainer" class="hidden">
                                <div class="flex items-center gap-4">
                                    <!-- Spinner -->
                                    <div class="relative">
                                        <div class="w-12 h-12 rounded-full border-4 border-blue-100 border-t-blue-500 animate-spin"></div>
                                        <div class="absolute inset-0 flex items-center justify-center">
                                            <i class="fas fa-file text-blue-500 text-sm"></i>
                                        </div>
                                    </div>
                                    <!-- Document Info -->
                                    <div class="flex-1">
                                        <div class="flex items-center gap-2 mb-1">
                                            <span class="font-medium">Processing Document</span>
                                            <span id="currentDocId" class="text-sm bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full"></span>
                                        </div>
                                        <div id="currentDocTitle" class="text-sm text-gray-600 truncate"></div>
                                    </div>
                                </div>
                            </div>

                            <div id="idleContainer" class="flex items-center gap-4">
                                <div class="w-12 h-12 rounded-full bg-gray-50 flex items-center justify-center">
                                    <i class="fas fa-check text-gray-400"></i>
                                </div>
                                <div>
                                    <div class="font-medium">System Idle</div>
                                    <div class="text-sm text-gray-600">Waiting for new documents</div>
                                </div>
                            </div>
                        </div>

                        <!-- Stats Grid -->
                        <div class="grid grid-cols-2 gap-4">
                            <!-- Today's Stats -->
                            <div class="bg-white rounded-xl border border-gray-100 p-4">
                                <div class="text-sm text-gray-600 mb-1">Processed Today</div>
                                <div class="flex items-end gap-2">
                                    <span id="processedToday" class="text-2xl font-bold">0</span>
                                    <span class="text-sm text-gray-500 mb-1">documents</span>
                                </div>
                            </div>

                            <!-- Last Processed -->
                            <div class="bg-white rounded-xl border border-gray-100 p-4">
                                <div class="text-sm text-gray-600 mb-1">Last Processed</div>
                                <div id="lastProcessed" class="text-sm font-medium"></div>
                            </div>
                        </div>
                    </div>
                
                    <!-- Token Distribution Chart -->
                    <div class="material-card">
                        <h3 class="card-title">Token Usage Distribution</h3>
                        <div class="chart-container">
                            <canvas id="tokenDistribution"></canvas>
                        </div>
                    </div>
                
                    <!-- Document Types Chart -->
                    <div class="material-card">
                        <h3 class="card-title">Document Type Distribution</h3>
                        <div class="chart-container">
                            <canvas id="documentTypes"></canvas>
                        </div>
                    </div>
                </div>
        </main>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuButton = document.getElementById('mobileMenuButton');
            const sidebar = document.querySelector('.sidebar');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            
            function toggleSidebar(event) {
                event.stopPropagation(); // Prevent event bubbling
                sidebar.classList.toggle('active');
                sidebarOverlay.classList.toggle('active');
                
                // Toggle menu icon
                const icon = mobileMenuButton.querySelector('i');
                if (sidebar.classList.contains('active')) {
                    icon.classList.remove('fa-bars');
                    icon.classList.add('fa-times');
                } else {
                    icon.classList.remove('fa-times');
                    icon.classList.add('fa-bars');
                }
            }

            // Toggle sidebar when clicking the menu button
            mobileMenuButton.addEventListener('click', toggleSidebar);

            // Close sidebar when clicking the overlay
            sidebarOverlay.addEventListener('click', function(event) {
                event.stopPropagation(); // Prevent event bubbling
                if (sidebar.classList.contains('active')) {
                    toggleSidebar(event);
                }
            });

            // Prevent sidebar from closing when clicking inside it
            sidebar.addEventListener('click', function(event) {
                event.stopPropagation();
            });

            // Handle links in sidebar
            const sidebarLinks = document.querySelectorAll('.sidebar-link');
            sidebarLinks.forEach(link => {
                link.addEventListener('click', function(event) {
                    // Don't prevent default here to allow navigation
                    event.stopPropagation();
                });
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            // Current Workload
            // Function to get the current theme
            function getCurrentTheme() {
                //return current theme (light or dark)
                return localStorage.getItem('theme') || 'light';
            }

            // Function to get the axis text color based on the current theme
            function getAxisTextColor() {
                return getCurrentTheme() === 'dark' ? '#ffffff' : '#000000';
            }

            // Token Distribution Chart
            new Chart(document.getElementById('tokenDistribution'), {
                type: 'bar',
                data: {
                    labels: <%- JSON.stringify(paperless_data.tokenDistribution.map(dist => dist.range)) %>,
                    datasets: [{
                        label: 'Number of Documents',
                        data: <%- JSON.stringify(paperless_data.tokenDistribution.map(dist => dist.count)) %>,
                        backgroundColor: '#60a5fa'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    scales: {
                        x: {
                            ticks: {
                                color: getAxisTextColor() // Set X-axis text color based on theme
                            }
                        },
                        y: {
                            ticks: {
                                color: getAxisTextColor() // Set Y-axis text color based on theme
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            labels: {
                                color: getAxisTextColor() // Set legend text color based on theme
                            }
                        }
                    }
                }
            });

            // Document Types Chart
            new Chart(document.getElementById('documentTypes'), {
                type: 'doughnut',
                data: {
                    labels: <%- JSON.stringify(paperless_data.documentTypes.map(type => type.type)) %>, // still need labels for tooltips
                    datasets: [{
                        data: <%- JSON.stringify(paperless_data.documentTypes.map(type => type.count)) %>,
                        backgroundColor: ['#3b82f6', '#60a5fa', '#93c5fd']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: false // This hides the labels/legend
                        },
                        tooltip: {
                            enabled: true // This ensures tooltips show on hover
                        }
                    }
                }
            });
        });
        async function checkForUpdates() {
            try {
                const currentVersion = '<%= version %>'.trim();
                if (!currentVersion) return;

                const response = await fetch('https://api.github.com/repos/clusterzx/paperless-ai/releases/latest');
                if (!response.ok) throw new Error('Failed to fetch release info');
                
                const data = await response.json();
                const latestVersion = data.tag_name;

                // Simple version comparison (assuming format like v1.0.0)
                const current = currentVersion.replace('v', '').split('.').map(Number);
                const latest = latestVersion.replace('v', '').split('.').map(Number);

                // Compare versions
                for (let i = 0; i < 3; i++) {
                    if ((latest[i] || 0) > (current[i] || 0)) {
                        // Set the latest version number
                        document.getElementById('latestVersion').textContent = latestVersion;
                        
                        // Show notification with animation
                        const notification = document.getElementById('updateNotification');
                        notification.classList.remove('hidden');
                        notification.style.opacity = '0';
                        notification.style.transform = 'translateY(20px)';
                        
                        // Animate in
                        setTimeout(() => {
                            notification.style.transition = 'all 0.3s ease-out';
                            notification.style.opacity = '1';
                            notification.style.transform = 'translateY(0)';
                        }, 100);
                        
                        break;
                    } else if ((latest[i] || 0) < (current[i] || 0)) {
                        break;
                    }
                }
            } catch (error) {
                console.error('Failed to check for updates:', error);
            }
        }
    </script>
    <script>
        window.dashboardData = {
            documentCount: <%= paperless_data.documentCount %>,
            processedCount: <%= paperless_data.processedDocumentCount %>
        };
    </script>
    <script>
        async function triggerScan() {
            const button = document.getElementById('scanButton');
            
            // If already scanning, prevent multiple clicks
            if (button.disabled) {
                return;
            }
            
            const icon = button.querySelector('i');
            const span = button.querySelector('span');
            
            // Disable button and show loading state
            button.disabled = true;
            button.classList.add('opacity-50', 'cursor-not-allowed');
            icon.classList.add('animate-spin');
            span.textContent = 'Scanning...';
            
            try {
                const response = await fetch('/api/scan/now', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error('Scan failed');
                }
                
                // Show success message
                const toast = document.getElementById('successToast');
                toast.classList.remove('hidden');
                
                // Hide success message after 3 seconds
                setTimeout(() => {
                    toast.classList.add('hidden');
                }, 3000);
                
            } catch (error) {
                console.error('Scan failed:', error);
                // Optional: Show error message to user
            } finally {
                // Reset button state
                button.disabled = false;
                button.classList.remove('opacity-50', 'cursor-not-allowed');
                icon.classList.remove('animate-spin');
                span.textContent = 'Scan Now';
            }
        }
        document.addEventListener('DOMContentLoaded', function() {
            checkForUpdates();
        });
    </script>
    <script>
        function formatTimeAgo(dateString) {
            const date = new Date(dateString + 'Z');
            const now = new Date();
            const seconds = Math.floor((now - date) / 1000);

            if (seconds < 5) {
                return 'just now';
            } else if (seconds < 60) {
                return `${seconds} seconds ago`;
            } else if (seconds < 3600) {
                const minutes = Math.floor(seconds / 60);
                return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
            } else if (seconds < 86400) {
                const hours = Math.floor(seconds / 3600);
                return `${hours} hour${hours > 1 ? 's' : ''} ago`;
            } else {
                const days = Math.floor(seconds / 86400);
                return `${days} day${days > 1 ? 's' : ''} ago`;
            }
        }

        function updateProcessingStatus() {
            fetch('/api/processing-status')
                .then(response => response.json())
                .then(data => {
                    console.log('Processing status data:', data);
                    
                    const processingContainer = document.getElementById('processingContainer');
                    const idleContainer = document.getElementById('idleContainer');
                    
                    if (data.currentlyProcessing) {
                        // Show processing state
                        processingContainer.classList.remove('hidden');
                        idleContainer.classList.add('hidden');

                        // disable scanButton if processing
                        document.getElementById('scanButton').disabled = true;
                                                
                        // Update document info
                        document.getElementById('currentDocId').textContent = `#${data.currentlyProcessing.documentId}`;
                        // Trim title to 50 characters and add ... if longer
                        data.currentlyProcessing.title = data.currentlyProcessing.title.length > 50
                            ? data.currentlyProcessing.title.slice(0, 90) + '...'
                            : data.currentlyProcessing.title;
                        document.getElementById('currentDocTitle').textContent = data.currentlyProcessing.title;
                        
                        // Show "Processing..."
                        document.getElementById('lastProcessed').innerHTML = `
                            <span class="text-blue-600">
                                <i class="fas fa-spinner fa-spin"></i> Processing...
                            </span>`;
                    } else {
                        // Show idle state
                        processingContainer.classList.add('hidden');
                        idleContainer.classList.remove('hidden');
                        // enable scanButton if idle
                        document.getElementById('scanButton').disabled = false;
                        if (data.lastProcessed) {
                            const timeAgo = formatTimeAgo(data.lastProcessed.processed_at);
                            console.log('Last processed:', data.lastProcessed.processed_at);
                            console.log('Formatted time:', timeAgo);
                            document.getElementById('lastProcessed').textContent = timeAgo;
                        } else {
                            document.getElementById('lastProcessed').textContent = 'No documents processed yet';
                        }
                    }
                    
                    // Update stats
                    document.getElementById('processedToday').textContent = data.processedToday;
                    
                    // Update timestamp
                    document.getElementById('statusLastUpdated').textContent = 
                        `Last updated: ${new Date().toLocaleTimeString()}`;
                })
                .catch(error => console.error('Error fetching processing status:', error));
        }

        // Update status every 3 seconds
        setInterval(updateProcessingStatus, 3000);

        // Initial update
        updateProcessingStatus();
    </script>
    <script>
        // get github stars count from repo
        async function getStarsCount() {
            try {
                const response = await fetch('https://api.github.com/repos/clusterzx/paperless-ai');
                if (!response.ok) throw new Error('Failed to fetch repo info');
                
                const data = await response.json();
                document.getElementById('starCount').textContent = data.stargazers_count.toLocaleString();
            } catch (error) {
                console.error('Failed to fetch stars count:', error);
            }
        }
        document.addEventListener('DOMContentLoaded', function() {
            getStarsCount();
        });
    </script>
    <script src="js/dashboard.js"></script>
</body>
</html>